// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod setup;
#[cfg(target_os = "macos")]
use cocoa::appkit::{NSWindow, NSWindowStyleMask, NSWindowTitleVisibility};

use tauri::{utils::config::AppUrl, window::WindowBuilder, Runtime, Window, WindowUrl, Manager, State};
use std::sync::Mutex;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Clone)]
struct VideoChatUser {
    userId: String,
    name: String,
    avatar: String,
}

struct VideoChatState {
    current_user: Mutex<Option<VideoChatUser>>,
}
pub trait WindowExt {
    #[cfg(target_os = "macos")]
    fn set_transparent_titlebar(&self, title_transparent: bool, remove_toolbar: bool);
}

impl<R: Runtime> WindowExt for Window<R> {
    #[cfg(target_os = "macos")]
    fn set_transparent_titlebar(&self, title_transparent: bool, remove_tool_bar: bool) {
        unsafe {
            let id = self.ns_window().unwrap() as cocoa::base::id;
            NSWindow::setTitlebarAppearsTransparent_(id, cocoa::base::YES);
            let mut style_mask = id.styleMask();
            style_mask.set(
                NSWindowStyleMask::NSFullSizeContentViewWindowMask,
                title_transparent,
            );

            if remove_tool_bar {
                style_mask.remove(
                    NSWindowStyleMask::NSClosableWindowMask
                        | NSWindowStyleMask::NSMiniaturizableWindowMask
                        | NSWindowStyleMask::NSResizableWindowMask,
                );
            }

            id.setStyleMask_(style_mask);

            id.setTitleVisibility_(if title_transparent {
                NSWindowTitleVisibility::NSWindowTitleHidden
            } else {
                NSWindowTitleVisibility::NSWindowTitleVisible
            });

            id.setTitlebarAppearsTransparent_(if title_transparent {
                cocoa::base::YES
            } else {
                cocoa::base::NO
            });
        }
    }
}

fn main() {
    let port = 50948;
    let url = format!("http://localhost:{}", port).parse().unwrap();
    let window_url = WindowUrl::External(url);
    let mut context = tauri::generate_context!();
    // rewrite the config so the IPC is enabled on this URL
    context.config_mut().build.dist_dir = AppUrl::Url(window_url.clone());
    context.config_mut().build.dev_path = AppUrl::Url(window_url.clone());

    tauri::Builder::default()
        .plugin(tauri_plugin_localhost::Builder::new(port).build())
        .manage(VideoChatState {
            current_user: Mutex::new(None),
        })
        .invoke_handler(tauri::generate_handler![
            open_video_chat_window,
            close_video_window,
            minimize_video_window,
            send_video_offer,
            send_video_answer,
        ])
        .setup(move |app| {
            WindowBuilder::new(app, "main".to_string(), window_url)
                .title("Localhost Example")
                .build()?;
            Ok(())
        })
        .setup(setup::init)
        .run(context)
        .expect("error while running tauri application");
}

#[tauri::command]
async fn open_video_chat_window(
    app: tauri::AppHandle,
    user: VideoChatUser,
    is_incoming: bool,
    state: State<'_, VideoChatState>,
) -> Result<(), ()> {
    // 存储当前用户信息
    {
        let mut current_user = state.current_user.lock().unwrap();
        *current_user = Some(user.clone());
    }
    
    // 先检查并关闭已存在的视频聊天窗口
    if let Some(existing_window) = app.get_window("video-chat") {
        existing_window.close().unwrap();
    }
    
    // 构建URL参数
    let user_param = serde_json::to_string(&user).unwrap();
    let url = format!("/#/video-chat?user={}&incoming={}", 
        urlencoding::encode(&user_param), 
        is_incoming
    );
    
    // 创建视频聊天窗口
    let window = tauri::WindowBuilder::new(
        &app,
        "video-chat",
        tauri::WindowUrl::App(url.into())
    )
    .title("视频通话")
    .center()
    .resizable(true)
    .decorations(false)
    .always_on_top(true)
    .inner_size(800.0, 600.0)
    .build()
    .unwrap();
    
    window.show().unwrap();
    Ok(())
}

#[tauri::command]
async fn close_video_window(app: tauri::AppHandle) -> Result<(), ()> {
    if let Some(window) = app.get_window("video-chat") {
        window.close().unwrap();
    }
    Ok(())
}

#[tauri::command]
async fn minimize_video_window(app: tauri::AppHandle) -> Result<(), ()> {
    if let Some(window) = app.get_window("video-chat") {
        window.minimize().unwrap();
    }
    Ok(())
}

#[tauri::command]
async fn send_video_offer(
    app: tauri::AppHandle,
    offer: String,
    target_user_id: String,
) -> Result<(), ()> {
    // 这里应该通过WebSocket发送offer到目标用户
    // 暂时只是打印日志
    println!("发送视频offer到用户: {}, offer: {}", target_user_id, offer);
    Ok(())
}

#[tauri::command]
async fn send_video_answer(
    app: tauri::AppHandle,
    answer: String,
    target_user_id: String,
) -> Result<(), ()> {
    // 这里应该通过WebSocket发送answer到目标用户
    // 暂时只是打印日志
    println!("发送视频answer到用户: {}, answer: {}", target_user_id, answer);
    Ok(())
}
